from django.shortcuts import render,redirect
from df_user.islogin import islogin
from df_cart.models import *
from df_goods.models import *
from df_user.models import *
from df_order.models import *
from django.http import JsonResponse,HttpResponse,HttpResponseRedirect
import ast
from django.utils import timezone

from decimal import Decimal
# Create your views here.
@islogin
def index(request):
    # 从session中获取当前用户的id
    # uid = request.session.get('user_id')
    # # 根据id搜索当前用户放入购物车中的品种
    # carts = CartInfo.objects.filter(user_id=uid)
    # # print(carts)
    # 从数据库中获取用户相关信息..
    user = UserInfo.objects.get(id=request.session['user_id'])
    phone = user.uphone[:3] + '****' + user.uphone[-4:]
    goodlistid = request.COOKIES.get('checkedid')
    goodslist = ast.literal_eval(goodlistid)
    # print(type(goodslist))
    list = []
    # print(goodslist)
    for id in goodslist:

        carts = CartInfo.objects.get(goods_id=id,user_id = user.id)
        list.append(carts)
    # print(list)


    context = {'title':'提交订单',
               'orders':1,
               'ushou': user.ushou,
               'uaddress': user.uaddress,
               'uyoubian': user.uyoubian,
               'uphone': phone,
                'carts' : carts,
                'carts2': list,
                 'count' : len(list),
               }
    return render(request,'df_order/place_order.html',context)

def get_checkedgoods(request):

    if request.method =='POST':
        post = request.POST
        goodsid = post.getlist('checkId')
        # print(goodsid)
        res = HttpResponse('/order/')

        res.set_cookie('checkedid',goodsid)
        return res
    return JsonResponse({'ok':0})

def add_checkedgoods(request):
    user = UserInfo.objects.get(id=request.session['user_id'])
    order_id = timezone.localtime().strftime('%m%d%H%M%S%f')
    phone = user.uphone
    addr = user.uaddress
    uid = user.id
    time = timezone.localtime().strftime('%Y-%m-%d %H:%M:%S')
    pay_status = '未支付'
    freight = '10'
    pay_method = ''
    total =0
    goodlistid = request.COOKIES.get('checkedid')
    goodslist = ast.literal_eval(goodlistid)
    spe_count = len(goodslist)

    if request.method == 'POST':
        pay_method = request.POST.get('pay_meth')
        total = request.POST.get('realtotal')
        # print(total)
        # print(goodslist,spe_count)
        order = OrderInfo()
        order.order_id= order_id
        order.o_phone = phone
        order.o_address = addr
        order.o_time = time
        order.o_paymethod = pay_method
        order.o_status = pay_status
        order.o_species_count = spe_count
        order.o_freight = freight
        order.o_total = float(total)
        order.user_id = uid
        order.save()

        for id in goodslist:
            goods = GoodsInfo.objects.get(id = id)
            cart = CartInfo.objects.get(user_id = uid,goods_id = id)
            goodinfo = Order_GoodsInfo()
            goodinfo.count =cart.count
            goodinfo.price = goods.gprice
            goodinfo.subtotal = int(cart.count) * int(goods.gprice)
            goodinfo.goods_id = id
            goodinfo.order_id = order_id
            goodinfo.save()

        return JsonResponse({'ok':1})

    return JsonResponse({
        'order_id':order_id,
        'phone':phone,
        'uid': uid,
        'addr':addr,
        'time':time,
        'pay_status':pay_status,
        'freight':freight,
        'pay_method': pay_method,
        'spe_count': spe_count,
        'total': total,

    })

def delete(request, orderid):
    print(type(orderid))
    try:
        order_good = Order_GoodsInfo.objects.filter(order_id = orderid)
        print(orderid)
        order_good.delete()
        order = OrderInfo.objects.get(order_id = orderid)
        order.delete()

        data = {'ok': 0}
    except Exception as e:
        print(e)
        data = {'ok': 1}

    return JsonResponse(data)